from PyPDF4 import PdfFileReader, PdfFileWriter
from PyPDF4.pdf import ContentStream
from PyPDF4.generic import TextStringObject, NameObject,NullObject
from PyPDF4.utils import b_
def remove_watermark(wm_text, inputFile, outputFile):
    with open(inputFile, "rb") as f:
        source = PdfFileReader(f, "rb")
        output = PdfFileWriter()

        for page_num in range(source.getNumPages()):
        # for page_num in range(1):
            page = source.getPage(page_num)
            # content  = page.extractText()
            # print(content)
            content_object = page["/Contents"].getObject()
            content = ContentStream(content_object, source)

            for operands, operator in content.operations:
                # print(operands)
                # print(operator)
                # print('-'*50)
                if  operator == b_("Do"):
                    print('*'*50)
                    print('*'*50)
                    print(operands[0])
                    if operands[0] == '/Image5':
                        operands[0] = NullObject()
            # #     if operator == b_("Tj"):
            #         text = operands[0]
            #
            #         if isinstance(text, str) and text.startswith(wm_text):
            #             operands[0] = TextStringObject('')
            #
            page.__setitem__(NameObject('/Contents'), content)
            output.addPage(page)

        with open(outputFile, "wb") as outputStream:
            output.write(outputStream)


wm_text = 'wm_text'
inputFile = r"C:\Users\YANG.LEI\Downloads\ling.pdf"
# inputFile = r"C:\Users\YANG.LEI\Downloads\sample.pdf"
outputFile = r"C:\Users\YANG.LEI\Downloads\ling1.pdf"
remove_watermark(wm_text, inputFile, outputFile)